package com.hbnu.dao;

import com.hbnu.pojo.Student;
import com.hbnu.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDao {
    Connection cn = null;

    PreparedStatement ps = null;

    ResultSet rs = null;

    //学生登录方法
    public Student login(Student loginStu){

        Student stu = new Student();//一定要初始化，空的构造方法

        try {
            //1.连接数据库
            cn = JDBCUtils.getConnection();

            //2.定义sql语句
            String sql = "select * from student where sname = ? and password = ?";

            //3.获取执行sql语句的prepareStatment对象
            ps = cn.prepareStatement(sql);

            ps.setString(1,loginStu.getSname());//填充？里的内容
            ps.setString(2,loginStu.getPassword());

            //4.执行sql语句(得到查询结果)
            rs = ps.executeQuery();


            if (rs.next()){//若有数据，则执行

                //4.获取rs结果集中的每个字段

                int id = rs.getInt("id");

                String sname = rs.getString("sname");

                int sex = rs.getInt("sex");

                //5.将查询结果放进stu对象
                stu.setId(id);
                stu.setSname(sname);
                stu.setSex(sex);

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtils.close(rs,ps,cn);
        }

        return stu;
    }
}